// 实习岗位业务逻辑层
package org.example.backend.service;

import org.example.backend.dto.InternshipPositionDto;
import org.example.backend.dto.InternshipPositionDetailDto;
import org.example.backend.entity.Company;
import org.example.backend.entity.InternshipPosition;
import org.example.backend.exception.ResourceNotFoundException;
import org.example.backend.repository.CompanyRepository;
import org.example.backend.repository.InternshipPositionRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class InternshipPositionService {

    private final InternshipPositionRepository internshipPositionRepository;
    private final CompanyRepository companyRepository;

    public InternshipPositionService(InternshipPositionRepository internshipPositionRepository, CompanyRepository companyRepository) {
        this.internshipPositionRepository = internshipPositionRepository;
        this.companyRepository = companyRepository;
    }

    /**
     * 发布实习岗位
     */
    public InternshipPosition createPosition(InternshipPositionDto positionDto, Long companyId) {
        InternshipPosition position = new InternshipPosition();
        position.setCompanyId(companyId);
        position.setTitle(positionDto.getTitle());
        position.setDescription(positionDto.getDescription());
        position.setRequirements(positionDto.getRequirements());
        position.setDepartment(positionDto.getDepartment());
        position.setWorkLocation(positionDto.getWorkLocation());
        position.setSalaryRange(positionDto.getSalaryRange());
        position.setWorkType(positionDto.getWorkType());
        position.setRecruitmentCount(positionDto.getRecruitmentCount());
        position.setDeadline(positionDto.getDeadline());
        position.setStatus(1); // 默认发布中

        return internshipPositionRepository.save(position);
    }

    /**
     * 更新实习岗位
     */
    public InternshipPosition updatePosition(Long positionId, InternshipPositionDto positionDto) {
        InternshipPosition position = internshipPositionRepository.findById(positionId)
                .orElseThrow(() -> new ResourceNotFoundException("实习岗位不存在"));

        position.setTitle(positionDto.getTitle());
        position.setDescription(positionDto.getDescription());
        position.setRequirements(positionDto.getRequirements());
        position.setDepartment(positionDto.getDepartment());
        position.setWorkLocation(positionDto.getWorkLocation());
        position.setSalaryRange(positionDto.getSalaryRange());
        position.setWorkType(positionDto.getWorkType());
        position.setRecruitmentCount(positionDto.getRecruitmentCount());
        position.setDeadline(positionDto.getDeadline());
        position.setStatus(positionDto.getStatus());

        return internshipPositionRepository.save(position);
    }

    /**
     * 获取岗位详情（包含公司名称）
     */
    @Transactional(readOnly = true)
    public InternshipPositionDetailDto getPositionWithCompanyInfo(Long positionId) {
        InternshipPosition position = internshipPositionRepository.findById(positionId)
                .orElseThrow(() -> new ResourceNotFoundException("实习岗位不存在"));

        Company company = companyRepository.findById(position.getCompanyId())
                .orElseThrow(() -> new ResourceNotFoundException("公司信息不存在"));

        InternshipPositionDetailDto dto = new InternshipPositionDetailDto();
        dto.setId(position.getId());
        dto.setCompanyId(position.getCompanyId());
        dto.setCompanyName(company.getName());  // 设置公司名称
        dto.setTitle(position.getTitle());
        dto.setDescription(position.getDescription());
        dto.setRequirements(position.getRequirements());
        dto.setDepartment(position.getDepartment());
        dto.setWorkLocation(position.getWorkLocation());
        dto.setSalaryRange(position.getSalaryRange());
        dto.setWorkType(position.getWorkType());
        dto.setRecruitmentCount(position.getRecruitmentCount());
        dto.setDeadline(position.getDeadline());
        dto.setStatus(position.getStatus());
        dto.setCreatedAt(position.getCreatedAt());
        dto.setUpdatedAt(position.getUpdatedAt());

        return dto;
    }

    /**
     * 获取岗位详情
     */
    @Transactional(readOnly = true)
    public InternshipPosition getPositionById(Long positionId) {
        return internshipPositionRepository.findById(positionId)
                .orElseThrow(() -> new ResourceNotFoundException("实习岗位不存在"));
    }

    /**
     * 根据企业ID获取实习岗位列表
     */
    @Transactional(readOnly = true)
    public Page<InternshipPosition> getPositionsByCompany(Long companyId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        return internshipPositionRepository.findByCompanyId(companyId, pageable);
    }

    /**
     * 获取企业发布的有效岗位
     */
    @Transactional(readOnly = true)
    public List<InternshipPosition> getActivePositionsByCompany(Long companyId) {
        return internshipPositionRepository.findByCompanyIdAndStatus(companyId, 1);
    }

    /**
     * 删除实习岗位（软删除）
     */
    public void deletePosition(Long positionId) {
        InternshipPosition position = internshipPositionRepository.findById(positionId)
                .orElseThrow(() -> new ResourceNotFoundException("实习岗位不存在"));

        position.setStatus(0); // 设置为已下线
        internshipPositionRepository.save(position);
    }

    /**
     * 上线/下线实习岗位
     */
    public InternshipPosition togglePositionStatus(Long positionId) {
        InternshipPosition position = internshipPositionRepository.findById(positionId)
                .orElseThrow(() -> new ResourceNotFoundException("实习岗位不存在"));

        // 切换状态：0->1, 1->0
        position.setStatus(position.getStatus() == 0 ? 1 : 0);
        return internshipPositionRepository.save(position);
    }

    /**
     * 分页查询所有实习岗位
     */
    @Transactional(readOnly = true)
    public Page<InternshipPositionDetailDto> getAllPositionsWithCompanyInfo(String title, String workLocation,
                                                                            Integer status, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        Page<InternshipPosition> positions = internshipPositionRepository.findByConditions(title, workLocation, status, pageable);

        return positions.map(position -> {
            InternshipPositionDetailDto dto = new InternshipPositionDetailDto();
            dto.setId(position.getId());
            dto.setCompanyId(position.getCompanyId());
            dto.setTitle(position.getTitle());
            dto.setDescription(position.getDescription());
            dto.setRequirements(position.getRequirements());
            dto.setDepartment(position.getDepartment());
            dto.setWorkLocation(position.getWorkLocation());
            dto.setSalaryRange(position.getSalaryRange());
            dto.setWorkType(position.getWorkType());
            dto.setRecruitmentCount(position.getRecruitmentCount());
            dto.setDeadline(position.getDeadline());
            dto.setStatus(position.getStatus());
            dto.setCreatedAt(position.getCreatedAt());
            dto.setUpdatedAt(position.getUpdatedAt());

            // 获取公司名称
            try {
                Company company = companyRepository.findById(position.getCompanyId()).orElse(null);
                if (company != null) {
                    dto.setCompanyName(company.getName());
                }
            } catch (Exception e) {
                // 忽略异常
            }

            return dto;
        });
    }
}
